#include "th.h"
#include <iostream>
using namespace std;
typedef unsigned char uint8;  
typedef unsigned int  uint16;  
typedef unsigned long uint32;  

#define HIGH_TIME 32  

int pinNumber =6;  //use gpio1 to read data  
uint32 databuf;  

uint8 readSensorData(void)  
{  
		uint8 crc;   
		uint8 i;  

		pinMode(pinNumber,OUTPUT); // set mode to output  
		digitalWrite(pinNumber, 0); // output a high level   
		delay(29);  
		digitalWrite(pinNumber, 1); // output a low level   
		//delayMicroseconds(40);
		pinMode(pinNumber, INPUT); // set mode to input  
		pullUpDnControl(pinNumber,PUD_UP);  

		delayMicroseconds(27);  
		if(digitalRead(pinNumber)==0) //SENSOR ANS  
		{  
				//while(!digitalRead(pinNumber)); //wait to high  
				for (int k=0;k<55;k++){
						if(!digitalRead(pinNumber))
								delayMicroseconds(3);
						else
								break;
				}

				for(i=0;i<32;i++)  
				{  
					//	while(digitalRead(pinNumber)); //data clock start  
					//	while(!digitalRead(pinNumber)); //data start  
						for (int j=0;j<55;j++){
							if(digitalRead(pinNumber))
								delayMicroseconds(3);
							else
								break;
						} 
						for (int j=0;j<55;j++){
							if(!digitalRead(pinNumber))
								delayMicroseconds(3);
							else
								break;
						}

						delayMicroseconds(HIGH_TIME);  
						databuf*=2;  
						if(digitalRead(pinNumber)==1) //1  
						{  
								databuf++;  
						}  
				}  
				/*
				for(i=0;i<8;i++)  
				{  
						while(digitalRead(pinNumber)); //data clock start  
						while(!digitalRead(pinNumber)); //data start  
						delayMicroseconds(HIGH_TIME);  
						crc*=2;    
						if(digitalRead(pinNumber)==1) //1  
						{  
								crc++;  
						}  
				}  
				*/
				return 1;  
		}  
		else  
		{  
				return 0;  
		}  
}  

void *get_th(void *arg)  
{  
		pinMode(pinNumber,OUTPUT); // set mode to output  
		digitalWrite(pinNumber,1); // output a high level   
		tem_hu *th=(tem_hu *)arg;
		//for(int i=0;i<3;i++){
		delay(3000);  
		if(readSensorData())  
		{  
				(*th).tem=(databuf>>8)&0xff;
				(*th).hum=(databuf>>24)&0xff;
				/*
				   cout<<((databuf)&0xff)<<endl;
				   cout<<((databuf>>16)&0xff)<<endl;
				   th.hum=(databuf>>8)&0xff+(databuf&0xff)/10;
				   printf("RH:%d.%d\n",(databuf>>24)&0xff,(databuf>>16)&0xff);   
				   printf("TMP:%d.%d\n",(databuf>>8)&0xff,databuf&0xff);  
				 */
				databuf=0;  
				//  if((*th).tem<50&&(*th).tem>0&&(*th).hum<90)
				//  break;
		}  
		else  
		{  
				databuf=0;  
		}  

}  
